package com.wt.wechatTools;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import com.wt.wechatTools.room.WorkDatabase;
import com.wt.wechatTools.room.dao.UserDao;
import com.wt.wechatTools.room.entity.UserEntity;
import com.wt.wechatTools.tools.MyRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FragmentLogin extends Fragment {
    private static final String TAG = "FragmentLogin";
    UserDao userDao;
    WorkDatabase workDatabase;
    private UserEntity userEntityRoot;
    private EditText editUsername;
    private EditText editPwd;
    private Button btnLogin;
    private Button btnRegister;

    public FragmentLogin() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化 sqlite
        workDatabase = WorkDatabase.getDataBase(getContext());
        userDao = workDatabase.getUserDao();
        new Thread(new Runnable() {
            @Override
            public void run() {
                userEntityRoot= userDao.getUser();
            }
        }).start();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View viewLogin = inflater.inflate(R.layout.fragment_login, container, false);
        editUsername = viewLogin.findViewById(R.id.editName);
        editPwd = viewLogin.findViewById(R.id.editPwd);
        btnLogin = viewLogin.findViewById(R.id.btnLogin);
        btnRegister = viewLogin.findViewById(R.id.btnRegister);

        //绑定数据
        editUsername.setText(userEntityRoot.getUserName().isEmpty() ? "" : userEntityRoot.getUserName());
        editPwd.setText(userEntityRoot.getPwd().isEmpty() ? "" : userEntityRoot.getPwd());

        /**
         * 登录
         */
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //准备数据
                String userName = editUsername.getText().toString();
                String pwd = editPwd.getText().toString();

                // https://blog.csdn.net/xxl6097/article/details/51075400
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("username", userName)
                        .add("pwd", pwd)
                        .build();
                Request request = new Request.Builder()
                        .url(MyRequest.proUrl + "login")
                        .post(requestBody)
                        //增加关闭连接，不让它保持连接。https://blog.csdn.net/zhangteng22/article/details/52233126
                        .addHeader("Connection", "close")
                        .build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "onFailure: " + e.getMessage());
                        call.cancel();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseString = response.body().string();
                        int responseCode = response.code();
                        if (responseCode != 200) {
                            //toast无法在主线程执行。参考：https://blog.csdn.net/weixin_39755659/article/details/89534773
                            Looper.prepare();
                            Toast toast = Toast.makeText(getContext(), "登录失败", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            Looper.loop();// 进入loop中的循环，查看消息队列
                        }
                        if (responseCode == 200) {
                            //序列化https://www.runoob.com/w3cnote/android-tutorial-json.html
                            try {
                                JSONObject jsonObject = new JSONObject(responseString);
                                //写入sqlite
                                //UserEntity userEntity = new UserEntity(userId, userName, pwd, jsonObject.getString("token"), null, null);
                                userEntityRoot.setPwd(pwd);
                                userEntityRoot.setUserName(userName);
                                userEntityRoot.setToken(jsonObject.getString("token"));
                                userEntityRoot.setRole(2);
                                userDao.update(userEntityRoot);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.d(TAG, "onResponse: 序列化出错了！");
                                call.cancel();
                                response.close();
                            }
                            //页面跳转
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    NavController nv = Navigation.findNavController(v);
                                    nv.navigate(R.id.action_fragmentLogin_to_fragmentHome);
                                }
                            });
                        }
                        response.close();
                    }
                });
            }
        });

        /**
         * 注册
         */
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController nv = Navigation.findNavController(v);
                nv.navigate(R.id.action_FragmentLogin_to_fragmentRegister);
            }
        });

        //隐藏底部导航栏
//        BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);
//        bottomNavigationView.setVisibility(View.GONE);

        return viewLogin;
    }
}